﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AMatysiak.Reflection
{
    [Serializable]
    public class ReflectionSerializer
    {
        public string Serialize()
        {
            Type type = this.GetType();

            PropertyInfo[] properties = type.GetProperties();

            StringBuilder builder = new StringBuilder();

            foreach (PropertyInfo property in properties)
            {
                object value = property.GetValue(this, null);
                builder.AppendFormat("{0}={1};", property.Name, value);
            }

            return builder.ToString();
        }

        public void Deserialize(string text)
        {
            Dictionary<string, object> values = new Dictionary<string, object>();

            string[] pairs = text.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);

            foreach (string pair in pairs)
            {
                string[] kv = pair.Split('=');
                values.Add(kv[0], kv[1]);
            }

            Type type = this.GetType();

            foreach (var kvp in values)
            {
                PropertyInfo property = type.GetProperty(kvp.Key);
                object value = Convert.ChangeType(kvp.Value, property.PropertyType);
                property.SetValue(this, value, null);
            }
        }
    }
}
